﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using PivotIO.XML;
using System.Configuration;
using System.IO;
using System.Linq;

namespace PivotIO.Tests
{
    class Utils
    {
        public static void TestInit()
        {
            // Delete all data files!
            ImageInfoIO.WaitTillIOFlushed();
            FacetCategoryIO.WaitTillIOFlushed();

            var dir = new DirectoryInfo(ConfigurationManager.AppSettings["ROOTXMLDirectory"]);
            if (dir.Exists)
                dir.Delete(true);
            CollectionInfoIO.ResetCache();
            ImageInfoIO.ResetCache();
        }

        public static void TestFinalize()
        {
            ImageInfoIO.WaitTillIOFlushed();
            FacetCategoryIO.WaitTillIOFlushed();
        }

        /// <summary>
        /// See if a render is pending or not for a particular collection.
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static bool RenderPending(int cId)
        {
            var dir = new DirectoryInfo(Path.Combine(ConfigurationManager.AppSettings["ROOTXMLDirectory"], "RenderUpdatesPending"));
            if (!dir.Exists)
                return false;

            return dir.EnumerateFiles().Where(f => Path.GetFileNameWithoutExtension(f.Name) == cId.ToString()).Any();
        }

        /// <summary>
        /// Load image data from a file.
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        internal static byte[] LoadImageData(string p)
        {
            var fi = new FileInfo(p);
            Assert.IsTrue(fi.Exists, string.Format("File {0} does not exist", fi.FullName));

            using (var reader = fi.OpenRead())
            {
                byte[] data = new byte[fi.Length];
                reader.Read(data, 0, (int)fi.Length);
                return data;
            }
        }
    }
}
